package com.example.mpd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mpd.entity.User;
import com.example.mpd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/user")
    public List query(){
        System.out.println("开始查询用户数据"); // 确认方法是否被调用
        List<User> list = userMapper.find();
        System.out.println(list);
        return list;
    }

    @GetMapping("/findAll")
    public List findAll(){
        List<User> userAndOrder = userMapper.findAllUserAndOrder();
        System.out.println(userAndOrder);
        return userAndOrder;
    }

    //条件查询
    @GetMapping("/findOne")
    public List<User> findByCond(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username","zhangsan");
        return userMapper.selectList(queryWrapper);
    }
    //分页查询
    @GetMapping("/user/findByPage")
    public IPage findByPage(){
        Page<User> page = new Page<>(0,2);
        IPage ipage = userMapper.selectPage(page, null);
        return ipage;
    }
    @PostMapping("/user")
    public String addUser(User user){
        int res = userMapper.add(user);
        if (res > 0){
            return "插入成功";
        }
        return "插入失败";
    }

    @GetMapping("/del/{id}")
    public String delUser(@PathVariable int id){
        int res = userMapper.delete(id);
        if (res > 0){
            return "删除成功";
        }
        return "删除失败";
    }
    @GetMapping("/select/{id}")
    public User findUserById(@PathVariable int id){
        User user = userMapper.findById(id);
        System.out.println(user);
        return user;
    }
    @PostMapping("/update")
    public String updateUser(User user){
        int res = userMapper.update(user);
        if (res > 0){
            return "更新成功";
        }
        return "更新失败";
    }
}
